package com.bvgol.examples.nio.groupchat;/**
 * @Classname GroupChatServer
 * @Description TODO
 * @Date 2021/6/21 14:36
 * @Created by GUOCHEN
 */



import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;

/**
 * @program: my-spring-completely
 * @description:
 * @author: GUOCHEN
 * @create: 2021/06/21 14:36
 */
public class GroupChatServer {
    private Selector selector;
    private ServerSocketChannel serverSocketChannel;
    private static final int port = 6667;


    /**
    初始化参数
     */
    public GroupChatServer() {
        try {

            this.selector = Selector.open();
            this.serverSocketChannel = ServerSocketChannel.open();
            //绑定
            serverSocketChannel.socket().bind(new InetSocketAddress(port));
            //设置为非阻塞
            serverSocketChannel.configureBlocking(false);
            //channel注册到selector 上
            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

            System.out.println("服务器启动成功,开始监听..............");
            this.listening();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void listening(){
        try {
            while (true){
//                System.out.println("-----------------");

                //为什么 这句不写`下面的进不去? 也就是 selector.selectNow() 与selector.selectedKeys()  有什么关系
                if (selector.selectNow()==0) {
//                    System.out.println("-----没有和事件-----");
                    continue;
                }

                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                Iterator<SelectionKey> selectionKeyIterator = selectionKeys.iterator();
                while (selectionKeyIterator.hasNext()){
                    SelectionKey selectionKey = selectionKeyIterator.next();
                    //需要的事件都列出来
                    if (selectionKey.isAcceptable()) {
                        System.out.println("接收,承认");
                        //接收,承认
                        SocketChannel accept = serverSocketChannel.accept();
                        accept.configureBlocking(false);
                        accept.register(selector,SelectionKey.OP_READ);
                        System.out.println(accept.getRemoteAddress()+" 上线 " );
                    }
                    if (selectionKey.isConnectable()) {
                        System.out.println("连接");
                        //连接
                    }
                    if (selectionKey.isValid()) {
                        //验证
                        System.out.println("验证");
                    }
                    if (selectionKey.isReadable()) {
                        //读
                        System.out.println("读");
                        this.readData(selectionKey);
                    }
                    if (selectionKey.isWritable()) {
                        //写
                        System.out.println("写");
                    }
                    //移除当前key
                    selectionKeyIterator.remove();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
        }
    }


    private void readData(SelectionKey key){
        SocketChannel channel = null;
        try {
            channel =(SocketChannel) key.channel();
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
            int read = channel.read(byteBuffer);
            if (read>0) {
                String msg = new String(byteBuffer.array());
                System.out.println("客户端 "+channel.getRemoteAddress()+" 发送的消息为: " + msg);
                //转发消息给其它客户端
                this.sendDataToOther(msg,channel);
            }
        } catch (IOException e) {
            System.out.println("读数据 发生异常");
            key.cancel();
            try {
                channel.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
        }
    }

    /**
     * 功能描述:
     * @param msg
     * @param exclude 排除
     * @return: void
     * @author: 郭辰
     * @date: 2021/6/21 15:39
     */
    private void sendDataToOther(String msg,SocketChannel exclude){
        System.out.println("服务器开始转发--msg = " + msg);
        //获取selector所有的channel
        //剔除自己
        for (SelectionKey key : selector.keys()) {

        }
        selector.keys().forEach(key -> {
            Channel channel = key.channel();
            if (channel instanceof  SocketChannel && channel!= exclude){
                try {
                    ((SocketChannel) channel).write(ByteBuffer.wrap(msg.getBytes()));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });


    }

    public static void main(String[] args) {
        new GroupChatServer();
    }
}
